﻿Imports Microsoft.VisualBasic.ApplicationServices
Imports DebugAssistant
Imports System.Configuration
Imports System.Network.Communication.Email
Imports System.Net.Mail

Namespace My

    Friend Class Settings

        Public Shared Property SendErrorMessageByMail() As Boolean = False

    End Class

    ' The following events are available for MyApplication:
    ' 
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication

        Private Sub MyApplication_Startup(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
            On Error Resume Next
            Dim exePath = IO.Path.Combine(My.Application.Info.DirectoryPath, My.Application.Info.AssemblyName & ".exe")
            Dim cfg = ConfigurationManager.OpenExeConfiguration(exePath)
            With cfg.AppSettings
                My.Settings.SendErrorMessageByMail = CBool(.Settings("SendErrorMessageByMail").Value)
            End With
            If My.Settings.SendErrorMessageByMail Then
                LibDebug.AuthorMail = New Email()
                With LibDebug.AuthorMail
                    .SmtpAddress = cfg.AppSettings.Settings("SmtpAddress").Value
                    .SmtpUserName = cfg.AppSettings.Settings("SmtpUserName").Value
                    .SmtpPassword = cfg.AppSettings.Settings("SmtpPassword").Value
                    .To = New MailAddress(cfg.AppSettings.Settings("MailTo").Value)
                End With
            End If
            Call Program.Main()
        End Sub

        Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
            Common.Debuger.TraceListener.WriteLine("{0}" & vbCrLf & "{1}.", e.Exception.Message, e.Exception.StackTrace.ToString())
            Debug.Close()
            If Settings.SendErrorMessageByMail Then
                Common.Debuger.SendMailToAuthor(LibDebug.AuthorMail)
                If IO.File.Exists("Data.log") Then Kill("Data.log")
                If IO.File.Exists("Trace.log") Then Kill("Trace.log")
            End If
            e.ExitApplication = True
        End Sub

    End Class

End Namespace